﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Media;
using MapGraph;
using Microsoft.Research.DynamicDataDisplay;
using Microsoft.Research.DynamicDataDisplay.DataSources;
using Microsoft.Research.DynamicDataDisplay.PointMarkers;

namespace WpfGraph.Worker
{
    public class PrintBackgroundWorker : BackgroundWorker
    {
        public PrintBackgroundWorker()
        {
            DoWork += PrintBackgroundWorker_DoWork;
            WorkerReportsProgress = true;
        }

        void PrintBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            var path = e.Argument as string;
            var files = Directory.GetFiles(path);
            foreach (var file in files)
            {

                List<Solution> mapInfoList = LoadMapInfo(file);
                int[] ids = new int[mapInfoList.Count];
                double[] xs = new double[mapInfoList.Count + 1];
                double[] ys = new double[mapInfoList.Count + 1];

                for (int i = 0; i < mapInfoList.Count; ++i)
                {
                    xs[i] = mapInfoList[i].obj1; // x-values are longitude
                    ys[i] = mapInfoList[i].obj2; // y-values are latitude
                }

                xs[mapInfoList.Count] = 1;
                ys[mapInfoList.Count] = 1;

                var xDataSource = new EnumerableDataSource<double>(xs);
                xDataSource.SetXMapping(x => Convert.ToDouble(x));

                var yDataSource = new EnumerableDataSource<double>(ys);
                yDataSource.SetYMapping(y => y);

                CompositeDataSource compositeDataSource = new CompositeDataSource(xDataSource, yDataSource);

                ReportProgress(0, compositeDataSource);
                Thread.Sleep(300);
            }

        }

        private static List<Solution> LoadMapInfo(string fileName)
        {
            var result = new List<Solution>();
            FileStream fs = new FileStream(fileName, FileMode.Open);
            StreamReader sr = new StreamReader(fs);

            string line = "";
            while ((line = sr.ReadLine()) != null)
            {
                line = line.ToString().Trim();
                if (line.StartsWith("//"))
                    continue;
                else
                {
                    string[] pieces = line.Split(' ');
                    double lat = Double.Parse(pieces[0]); // 
                    double lon = Double.Parse(pieces[1]); // 
                    Solution mi = new Solution(lat, lon);
                    result.Add(mi);
                }
            }
            sr.Close();
            fs.Close();
            return result;
        }
    }
}
